package com.citycloud.datac.client.token;

import java.util.Arrays;
import java.util.Map;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;

import com.citycloud.datac.client.client.DataCOauth2Client;
import com.citycloud.datac.client.constants.CurrentProject;
import com.citycloud.datac.client.constants.CurrentUser;
import com.citycloud.datac.client.constants.OauthConstant;
import com.citycloud.datac.client.dto.DetailedUserInfo;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by : liujw Date 2018/3/28 0:53 Description：封装集成认证后的获取用户信息
 */
@Slf4j
@Component
@AllArgsConstructor
public class OauthUserService {

	@Autowired
	DataCOauth2Client oauth2Client;

	@Autowired
	private HttpServletRequest httpServletRequest;

	private RestOperations restTemplate;

	@Value("${security.oauth2.client.address}")
	private String accessTokenUri;

	/**
	 * 从 request 中获取token
	 *
	 * @param request
	 * @return
	 */
	public String getToken(HttpServletRequest request) {
		String token = StringUtils.isEmpty(request.getParameter(OauthConstant.TOKEN))
				? request.getParameter(OauthConstant.ACCESS_TOKEN)
				: request.getParameter(OauthConstant.TOKEN);
		if (StringUtils.isEmpty(token)) {
			token = StringUtils.isEmpty(request.getHeader(OauthConstant.TOKEN))
					? request.getHeader(OauthConstant.ACCESS_TOKEN)
					: request.getHeader(OauthConstant.TOKEN);
		}
		return token;
	}

	public OauthUserService() {
		restTemplate = new RestTemplate();

		/*
		 * 在非MVC的Project中使用RestTemplate.会报错 Could not extract response: no suitable
		 * HttpMessageConverter found for response type ***这个异常 简单的说， message converters
		 * 是负责 Java Object 和 Http 上的 JSON/XML互相转换的中介工具。
		 * 如果是在非MVC的Project中，根本就不会产生HttpMessageConverter ，此时使用RestTemplate会报如上所示的错误。
		 */

		MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
		mappingJackson2HttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON));
		((RestTemplate) restTemplate).getMessageConverters().add(mappingJackson2HttpMessageConverter);
	}

	private Map<String, Object> postForMap(String path, MultiValueMap<String, String> formData, HttpHeaders headers) {
		if (headers.getContentType() == null) {
			headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
		}

		Map map = (Map) this.restTemplate
				.exchange(path, HttpMethod.POST, new HttpEntity(formData, headers), Map.class, new Object[0]).getBody();
		return map;
	}

	/**
	 * 获取当前登录用户信息
	 *
	 * @return
	 */
	public CurrentUser getCurrentUser(String token) {
		if (StringUtils.isBlank(token)) {
			token = getToken(httpServletRequest);
		}
		DetailedUserInfo userInfo = oauth2Client.getUserInfo(token);
		CurrentUser currentUser = new CurrentUser();
		currentUser.setDispName(userInfo.getUserName());
		currentUser.setUserId(Objects.toString(userInfo.getUserId()));
		currentUser.setUserNo(userInfo.getUserNo());
		currentUser.setDeptName(userInfo.getDeptName());
		currentUser.setDeptId(userInfo.getDeptId());
		currentUser.setProjectId(userInfo.getCurrentSiteId());
		currentUser.setProjectName(userInfo.getCurrentSiteName());

		currentUser.setPlatformId(Long.valueOf(userInfo.getPlatformId()));

		return currentUser;
	}

	/**
	 * 获取当前访问站点
	 *
	 * @return
	 */
	public Long getCurrentUserPeojectId(String token) {
		return getCurrentUser(token).getProjectId();
	}

	/**
	 * 获取当前登录用户的站点信息
	 *
	 * @param token
	 * @return
	 */
	public CurrentProject getCurrentUserPeoject(String token) {
		CurrentUser currentUser = getCurrentUser(token);
		CurrentProject currentProject = new CurrentProject();
		currentProject.setWebsiteId(Objects.toString(currentUser.getProjectId()));
		currentProject.setName(currentUser.getProjectName());
		return currentProject;
	}

	/**
	 * 查看当前登录用户是否为平台站点管理员。
	 *
	 * @param token
	 * @return
	 */
	public Boolean isPlatFormSite(String token) {
		CurrentUser currentUser = getCurrentUser(token);
		String platformId = Objects.toString(currentUser.getPlatformId());
		if ("72".equals(Objects.toString(platformId))) {
			return true;
		}
		return false;
	}

	//////////////////////////////////////// 以下为集成海关认证获取用户信息等接口///////////////

//    @Autowired
//    private IUserService userService;
//
//    @Autowired
//    private HttpSession httpSession;
//
//    /**
//     * 获取当前登录用户信息
//     *
//     * @return
//     */
//    public CurrentUser getCurrentUser(String token) {
//        SecUser secUser = (SecUser) userService.getCurrentUser(token).getResultObject();
//
//        CurrentUser currentUser = new CurrentUser();
//        currentUser.setAllPathName(secUser.getAllPathName());
//        currentUser.setDispName(secUser.getDispName());
//        currentUser.setObjId(secUser.getObjId());
//        currentUser.setUserId(secUser.getUserId());
//        //站点
//        Object stationId = httpSession.getAttribute(QcloudConstant.SESSION_CURRENT_SITE_ID);
//        Long projectId;
//        if (stationId != null) {
//            projectId = Long.valueOf(Objects.toString(stationId));
//            currentUser.setProjectId(projectId);
//            Object name = httpSession.getAttribute(QcloudConstant.PRO_WEBSITE_NAME);
//            currentUser.setProjectName((Objects.toString(name)));
//        }
//        return currentUser;
//    }
//
//    /**
//     * 获取当前访问站点
//     *
//     * @return
//     */
//    public Long getCurrentUserPeojectId(String token) {
//        Object stationId = httpSession.getAttribute(QcloudConstant.SESSION_CURRENT_SITE_ID);
//        Long projectId = Long.MIN_VALUE;
//        if (stationId != null) {
//            projectId = Long.valueOf(Objects.toString(stationId));
//        }
//        log.error("当前用户站点id:{}", projectId);
//        return projectId;
//    }
//
//    /**
//     * 获取当前登录用户的站点信息
//     *
//     * @param token
//     * @return
//     */
//    public CurrentProject getCurrentUserPeoject(String token) {
//        CurrentProject currentProject = new CurrentProject();
//        Object stationId = httpSession.getAttribute(QcloudConstant.SESSION_CURRENT_SITE_ID);
//        if (stationId != null) {
//            currentProject.setWebsiteId(Objects.toString(stationId));
//            Object name = httpSession.getAttribute(QcloudConstant.PRO_WEBSITE_NAME);
//            currentProject.setName(Objects.toString(name));
//        }
//        return currentProject;
//    }
//
//    /**
//     * 判断当前用户是否为平台站点
//     *
//     * @param token
//     * @return
//     */
//    public Boolean isPlatFormSite(String token) {
//        Object stationId = httpSession.getAttribute(QcloudConstant.SESSION_CURRENT_SITE_ID);
//        if (stationId != null) {
//            if ("72".equals(Objects.toString(stationId))) {
//                return true;
//            }
//        }
//        return false;
//    }
}
